﻿using MediatR;
using Sowrk03_28.Repository;
using Swork03_28.Api.Application.Commands.FarmedCommand;
using Swork03_28.Domain;
using Swork03_28.Domain.TraceableInfos;
using Swork03_28.Services.Interface;

namespace Swork03_28.Api.Application.CommandHandlers.FarmedHandler
{
    public class FarmedCreateCommandHandler : IRequestHandler<FarmedCreateCommand, int>
    {
        private readonly IFarmedService farmedService;

        public FarmedCreateCommandHandler(IFarmedService farmedService)
        {
            this.farmedService = farmedService;
        }

        public async Task<int> Handle(FarmedCreateCommand request, CancellationToken cancellationToken)
        {
            var info = await farmedService.GetValues(x => x.BatchId == request.BatchId);
            var res = info.FirstOrDefault();
            if (res != null)
            {
                res.Id = res.Id;
                res.Certificate = request.Certificate;
                res.Source = request.Source;
                res.Feeding = request.Feeding;
                res.BatchId = request.BatchId;
                res.Breed = request.Breed;
                res.Brand=request.Brand;
                res.FarmId = res.FarmId;
                res.PublicationDate = request.PublicationDate;
                res.Principal = request.Principal;
                return await farmedService.UpdateAsync(res);
            }
            else
            {
                return await farmedService.CreateAsync(new Farmed()
                {
                    Certificate = request.Certificate,
                    Feeding = request.Feeding,
                    PublicationDate = request.PublicationDate,
                    Brand = request.Brand,
                    Breed = request.Breed,
                    BatchId = request.BatchId,
                    Source = request.Source,
                    FarmId = request.FarmId,
                    Principal = request.Principal
                });
            }
        }
    }
}
